import styles from "../style.module.less";
export default defineComponent({
  props: {
    modelValue: {
      type: Array,
      default: () => [],
    },
    userId: {
      type: String,
      default: "",
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    isShowTagSelect: {
      type: Boolean,
      default: false,
    },
  },
  emits: ["update:modelValue", "update:isShowTagSelect"],
  setup(props, { attrs, emit, expose, slots }) {
    const loading = ref(false);
    const fetchTagGroupList = async () => {
      try {
        loading.value = true;
        const res: any = await userApi.queryDicts({
          userId: props.userId,
        });
        if (res.code != 200) return message.error(res.message);
        let systemTags = res?.data?.systemTags || [];
        let userTags = res?.data?.userTags || [];
        const renderTree = (data: any, rootName: string) => {
          return data.map((item: any) => {
            if (item.children)
              return {
                title: item.tag_name,
                checkable: false,
                key: `${rootName}&${item.tag_id}&${item.tag_name}`,
                children: renderTree(item.children, rootName),
              };
            return {
              title: item.tag_name,
              checkable: true,
              key: `${rootName}&${item.tag_id}&${item.tag_name}`,
            };
          });
        };
        tagGroupList.value = [
          {
            title: $t("party2"),
            key: $t("party2"),
            checkable: false,
            children: renderTree(userTags, $t("party2")),
          },
          {
            title: $t("party3"),
            key: $t("party3"),
            checkable: false,
            children: renderTree(systemTags, $t("party3")),
          },
        ];
      } catch (error: any) {
        message.error(error.message);
      } finally {
        loading.value = false;
      }
    };
    const handleClear = (key?: string) => {
      if (key)
        checkedKeys.value = checkedKeys.value.filter((item) => item !== key);
      else checkedKeys.value = [];
    };
    const handleOk = () => {
      emit("update:modelValue", checkedTags.value);
      emit("update:isShowTagSelect", false);
    };
    const tagGroupList: any = ref([]);
    const onCheckTree = (keys: any) => {
      if (keys.length > 10) message.warning($t("party4"));
      checkedKeys.value = keys.slice(0, 10);
    };
    const checkedKeys = ref<string[]>(
      props.modelValue.map((item: any) => item.key)
    );
    watchEffect(() => {
      if (props.isShowTagSelect) {
        checkedKeys.value = props.modelValue.map((item: any) => item.key);
      }
    });
    const checkedTags = computed(() => {
      return checkedKeys.value
        .map((val) => {
          const [group, key, title] = val?.split("&");
          return {
            group,
            key: val,
            title,
          };
        })
        .filter((item) => item.group !== $t("party5"));
    });

    fetchTagGroupList();
    return () => (
      <>
        <div {...attrs}>
          {props.isEdit
            ? props.modelValue.map((item: any) => (
                <a-tag
                  closable
                  key={item.key}
                  onClose={() => {
                    handleClear(item.key);
                    emit("update:modelValue", checkedTags.value);
                  }}
                >
                  {item.title}
                </a-tag>
              ))
            : props.modelValue.map((item: any) => <a-tag>{item}</a-tag>)}
        </div>
        <a-modal
          visible={props.isShowTagSelect}
          onUpdate:visible={(val: boolean) =>
            emit("update:isShowTagSelect", val)
          }
          title={$t("party6")}
          width="800px"
          centered
        >
          {{
            footer: () => (
              <>
                <div style="width: 100%;display: flex;gap: 20px;justify-content: center;margin: 16px 0 0;">
                  <a-button
                    onClick={() => emit("update:isShowTagSelect", false)}
                  >
                    {$t("base.cancel")}
                  </a-button>
                  <a-button type="primary" onClick={handleOk}>
                    {$t("base.ok")}
                  </a-button>
                </div>
              </>
            ),
            default: () => (
              <>
                <a-spin spinning={loading.value}>
                  <div style="width: 100%;height: 400px;display: flex;justify-content: space-between;">
                    <div style="overflowY: auto;width: 240px;">
                      <a-tree
                        v-model:checkedKeys={checkedKeys.value}
                        checkable
                        treeData={tagGroupList.value}
                        virtual={false}
                        onCheck={onCheckTree}
                      >
                        {{
                          title: ({ title, key }: any) => <>{title}</>,
                        }}
                      </a-tree>
                    </div>
                    <div style="width: 300px;background: #f4f3f3;padding: 7px 9px;display: flex;flex-direction: column">
                      <div style="display: flex;justify-content: space-between;align-items: center;">
                        <span>
                          {$t("party7")} {checkedTags.value.length}
                          {$t("party8")}
                        </span>
                        <a-button type="link" onClick={() => handleClear()}>
                          {$t("base.clear")}
                        </a-button>
                      </div>
                      <div style="flex: 1;overflow-Y: auto;padding: 0px 10px;">
                        {checkedTags.value.map((item, index) => (
                          <div
                            key={item.key}
                            style="display: flex;fontSize: 12px;align-items: center;justify-content: space-between;margin: 4px 0;"
                          >
                            <div style="display: flex;align-items: center;gap: 10px;">
                              <div
                                class={styles.color}
                                style="border: 1px solid #91D5FF;background-color: #e6f7ff;border-radius: 2px;padding: 1px 15px;"
                              >
                                {item.group}
                              </div>
                              {item.title}
                            </div>
                            <a-button
                              type="link"
                              size="small"
                              onClick={() => handleClear(item.key)}
                            >
                              <minus-outlined style="font-weight: bold" />
                            </a-button>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                </a-spin>
              </>
            ),
          }}
        </a-modal>
      </>
    );
  },
});
